package controller

import (
	"github.com/brocaar/chirpstack-api/go/v3/nc"
	"github.com/pkg/errors"
	"google.golang.org/grpc"
	"google.golang.org/grpc/balancer/roundrobin"
	"network/v3/internal/config"
	log "network/v3/pkg/logger"
)

var client nc.NetworkControllerServiceClient

// init sets the NopNetworkControllerClient by default, as the client is optional.
func init() {
	client = &NopNetworkControllerClient{}
}

// SetClient sets up the given controller client.
func SetClient(c nc.NetworkControllerServiceClient) {
	client = c
}

// Client returns the controller cient.
func Client() nc.NetworkControllerServiceClient {
	return client
}

func SetupNetworkController(c config.Config) error {
	if c.NetworkController.Server != "" {
		log.WithFields(log.Fields{
			"server": c.NetworkController.Server,
		}).Info("connecting to network-controller")
		ncDialOptions := []grpc.DialOption{
			grpc.WithDefaultServiceConfig(roundrobin.Name),
			grpc.WithInsecure(),
		}
		ncConn, err := grpc.Dial(c.NetworkController.Server, ncDialOptions...)
		if err != nil {
			return errors.Wrap(err, "network-controller dial error")
		}
		ncClient := nc.NewNetworkControllerServiceClient(ncConn)
		SetClient(ncClient)
	}

	return nil
}
